package com.my.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.my.reggie.common.BaseContext;
import com.my.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class loginFilter implements Filter {
    // 路径匹配其，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // log.info("拦截到请求:{}",request.getRequestURI());
        // 1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        // log.info("拦截到请求:{}",requestURI);
        // 2.定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",  //移动端发送短信
                "/user/login",    //移动端登录
                "/user/logout",
                "/doc.html",     //swagger API
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/api/wx-pay/native/notify",   //支付通知地址
                "/api/wx-pay/refunds/notify",   //退款通知地址
        };
        // 3.判断本次请求是否需要处理
        if (check(urls, requestURI)) {
            log.info("本次请求不需要处理{}",requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        // 4.1判断是否已经登录
        if (request.getSession().getAttribute("employee") != null
                && !requestURI.contains("user") && !requestURI.contains("shoppingCart")) {
            //log.info("用户已登录");
            // 设置当前登录用户id
            Long emId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(emId);

            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 4.2判断移动端是否已经登录
        if (request.getSession().getAttribute("user") != null && !requestURI.contains("employee")) {
            // log.info("用户已登录");
            // 设置当前登录用户id
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 5.拦截
        log.warn("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }


    /**
     * 路径匹配判断
     * @param urls
     * @param URI
     * @return
     */
    public boolean check(String[] urls, String URI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, URI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}

